﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZLB_Dal.Upload;
using ZLB_Model.Database;
using ZLB_Model.Hospital;
using ZLB_Model.PDF;
using ZLB_Model.Results;
using ZLB_Model.TiJian;
using ZLB_Service.Basic;
using ZLB_Service.Hospital_Config;
using ZLB_Unility.Common;
using ZLB_Unility.Enums;
using ZLB_Unility.Extendsions;
using ZLB_Unility.Results;

namespace ZLB_Service.TiJian
{
    public class PDFService : BaseService
    {
        private ZLB_ReportUploadDal ZLB_ReportUploadDal = new ZLB_ReportUploadDal();
        private WebUtils WebUtils = new WebUtils();

        public ResultInfo InitPDF()
        {
            List<TiJianB> listTJB = HospiatlManager.PhysicalDal.GetTiJianBList();
            if (listTJB == null || listTJB.Count == 0)
                return CodeStatus.error_201.GetStatus("无待传数据");
            List<string> listSerialNo = ZLB_ReportUploadDal.GetAsNoTracking(a => true).Select(a => a.physical_serial_no).ToList();
            listTJB.RemoveAll(a => listSerialNo.Contains(a.TiJianLSH));

            if (listTJB == null || listTJB.Count == 0)
                return CodeStatus.error_201.GetStatus("无待传数据");

            List<ZLB_ReportUpload> listZLBReportUpload = GetZLBReportUploadList(listTJB);

            string errorMsg = string.Empty;

            bool b = HospiatlManager.PhysicalDal.sqlHelper.InsBulkCopy(listZLBReportUpload, ref errorMsg);
            if (!b)
                return CodeStatus.error_223.GetStatus(errorMsg);

            return CodeStatus.success.GetStatus();
        }

        public ResultInfo AutoPDF()
        {
            int init = EnumManager.init_code;
            int is_pdf = EnumManager.pdf_exist;
            ZLB_ReportUpload zlbReportUpload = ZLB_ReportUploadDal.Get(a => a.pdf_status == init && a.is_pdf == is_pdf).OrderByDescending(a => a.physical_serial_no).FirstOrDefault();
            if (zlbReportUpload == null)
                return CodeStatus.error_202.GetStatus("无PDF待传数据");


            XmlPDFBody xmlPDFBody = GetXmlPDFBody(zlbReportUpload);
            string xmlHeader = base.GetXmlHeader(BaseYY.pdf_api);
            string xmlBody = JsonXmlUtils.XmlSerialize(xmlPDFBody);

            IDictionary<string, object> dicParamter = GetParameter(xmlHeader, xmlBody);

            string result = WebUtils.HttpPostWebService(BaseYY.base_url, "doService", dicParamter);

            ZLBResultBody zlbResultBody = JsonXmlUtils.DeserializeXML<ZLBResultBody>(result);
            if (zlbResultBody.result.return_code == "1")
            {
                zlbReportUpload.pdf_status = EnumManager.pdf_success_code;
                zlbReportUpload.pdf_status_name = EnumManager.pdf_success_name;
                zlbReportUpload.pdf_id = zlbResultBody.msg.bq_report_pdf_id;
                zlbReportUpload.operate_time = DateTime.Now;
            }
            else
            {
                zlbReportUpload.pdf_status = EnumManager.pdf_fail_code;
                zlbReportUpload.pdf_status_name = EnumManager.pdf_fail_name;
                zlbReportUpload.operate_time = DateTime.Now;
            }

            if (!ZLB_ReportUploadDal.Up(zlbReportUpload))
                return CodeStatus.error_301.GetStatus("修改记录失败");

            return CodeStatus.success.GetStatus();
        }

        public ResultInfo EditPDFInit(string tjh)
        {
            if (string.IsNullOrEmpty(tjh))
                return CodeStatus.error_201.GetStatus($"{nameof(tjh)}为空");

            TiJianB tjb = HospiatlManager.PhysicalDal.GetTiJianB(tjh);
            if (tjb == null)
                return CodeStatus.error_202.GetStatus("无体检数据");

            ZLB_ReportUpload zlbReportUpload = ZLB_ReportUploadDal.Get(a => a.physical_serial_no == tjb.TiJianLSH).FirstOrDefault();
            if (zlbReportUpload == null)
                return CodeStatus.error_202.GetStatus("无待传记录");

            // 重传
            if (zlbReportUpload.pdf_status == EnumManager.pdf_success_code)
            {
                zlbReportUpload.pdf_status = EnumManager.init_code;
                zlbReportUpload.pdf_status_name = EnumManager.init_name;
                zlbReportUpload.is_pdf = EnumManager.pdf_init;
            }
            else
                zlbReportUpload = GetZLBReportUpload(zlbReportUpload, tjb);

            zlbReportUpload.up_time = DateTime.Now;

            if (!ZLB_ReportUploadDal.Up(zlbReportUpload))
                return CodeStatus.error_301.GetStatus("修改失败");

            return CodeStatus.success.GetStatus();
        }

        private IDictionary<string, object> GetParameter(string xmlHeader, string xmlBody)
        {
            IDictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("HeaderInParm", xmlHeader);
            dic.Add("BodyInParm", xmlBody);

            return dic;
        }

        private XmlPDFBody GetXmlPDFBody(ZLB_ReportUpload zlbReportUpload)
        {
            XmlPDFBody body = new XmlPDFBody();
            body.patient_name = zlbReportUpload.name;
            body.patient_idcard_type = "01";
            body.patient_idcard_value = zlbReportUpload.idcard;
            body.patient_age = zlbReportUpload.age;
            body.patient_sex = zlbReportUpload.sex;
            body.patient_phone = zlbReportUpload.phone;
            if (HospiatlManager.is_sms && ToolHelper.IsPhone(zlbReportUpload.phone))
                body.sms = "1";
            else
                body.sms = "0";

            body.med_org_report_id = zlbReportUpload.physical_no;
            body.med_org_report_pdf_id = zlbReportUpload.physical_no;
            body.examination_date = zlbReportUpload.physical_time;
            body.report_date = zlbReportUpload.report_time;
            body.reprot_type = "PE";

            byte[] bys = new byte[0];
            if (HospiatlManager.is_web)
                bys = WebUtils.GetByteByRemoteURL(zlbReportUpload.pdf_path);
            else
                bys = File.ReadAllBytes(zlbReportUpload.pdf_path);

            body.reprot_pdf = Convert.ToBase64String(bys);

            return body;
        }

        private List<ZLB_ReportUpload> GetZLBReportUploadList(List<TiJianB> listTJB)
        {
            List<ZLB_ReportUpload> listZLBReportUpload = new List<ZLB_ReportUpload>();

            foreach (TiJianB tjb in listTJB)
            {
                ZLB_ReportUpload ZLB_ReportUpload = new ZLB_ReportUpload();
                if (string.IsNullOrEmpty(HospiatlManager.base_path))
                    continue;
                if (HospiatlManager.is_web && !HospiatlManager.base_path.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
                    continue;

                ZLB_ReportUpload.physical_serial_no = tjb.TiJianLSH;
                ZLB_ReportUpload.physical_no = tjb.TiJianH;
                ZLB_ReportUpload.create_time = DateTime.Now;
                ZLB_ReportUpload.hospital_name = HospiatlManager.hospital_name;

                ZLB_ReportUpload = GetZLBReportUpload(ZLB_ReportUpload, tjb);

                ZLB_ReportUpload = GetZLBReportUploadStatus(ZLB_ReportUpload);

                listZLBReportUpload.Add(ZLB_ReportUpload);

            }
            return listZLBReportUpload;
        }

        private ZLB_ReportUpload GetZLBReportUpload(ZLB_ReportUpload ZLB_ReportUpload, TiJianB tjb)
        {
            ZLB_ReportUpload.idcard = StringUtils.ReplaceEmpty(tjb.ShenFenZhengH);
            ZLB_ReportUpload.name = StringUtils.ReplaceEmpty(tjb.XingMing);
            ZLB_ReportUpload.phone = StringUtils.ReplaceEmpty(tjb.ShouJiH);
            ZLB_ReportUpload.sex = StringUtils.ReplaceEmpty(tjb.XingBie);
            ZLB_ReportUpload.age = base.ConvertAge(tjb.NianLing, tjb.ShenFenZhengH);
            ZLB_ReportUpload.pdf_path = HospiatlManager.base_path + "/" + tjb.TiJianH + ".pdf";
            ZLB_ReportUpload.physical_time = base.ConvertTime(tjb.TiJianRQ);
            ZLB_ReportUpload.register_time = base.ConvertTime(tjb.DengJiRQ);
            ZLB_ReportUpload.report_time = base.ConvertTime(tjb.ZongJianRQ);
            ZLB_ReportUpload.is_web = HospiatlManager.is_web;
            ZLB_ReportUpload.is_pdf = EnumManager.pdf_init;

            return ZLB_ReportUpload;
        }

        private ZLB_ReportUpload GetZLBReportUploadStatus(ZLB_ReportUpload ZLB_ReportUpload)
        {
            ZLB_ReportUpload.pdf_status = EnumManager.init_code;
            ZLB_ReportUpload.pdf_status_name = EnumManager.init_name;
            ZLB_ReportUpload.data_status = EnumManager.init_code;
            ZLB_ReportUpload.data_status_name = EnumManager.init_name;

            if (string.IsNullOrWhiteSpace(ZLB_ReportUpload.idcard))
            {
                ZLB_ReportUpload.pdf_status = EnumManager.error_code;
                ZLB_ReportUpload.pdf_status_name = EnumManager.error_name;
                ZLB_ReportUpload.error_msg = "身份证号为空";
            }

            if (!ToolHelper.IsIDCard(ZLB_ReportUpload.idcard))
            {
                ZLB_ReportUpload.pdf_status = EnumManager.error_code;
                ZLB_ReportUpload.pdf_status_name = EnumManager.error_name;
                ZLB_ReportUpload.error_msg = "身份证号不合法";
            }

            return ZLB_ReportUpload;
        }

    }
}
